//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.IdentityModel.Tokens;
using System.IdentityModel.Claims;
using System.ServiceModel;
using System.IdentityModel.Policy;
using System.Web.Security;

namespace Shp.Security.BrokeredReceiver
{
    /// <summary>
    /// The authorization security token service.
    /// </summary>
    public class AuthorizationSecurityTokenService : SecurityTokenService
    {
        /// <summary>
        /// Sets up the AuthorizationSecurityTokenService by loading relevant Application Settings
        /// </summary>
        public AuthorizationSecurityTokenService()
            : base(ServiceConfiguration.SecurityTokenServiceName,
                   FederationUtilities.GetX509TokenFromCert(
                        ServiceConfiguration.StsStoreName, 
                        ServiceConfiguration.StsStoreLocation, 
                        ServiceConfiguration.StsDistinguishedName),
                   FederationUtilities.GetScopedTokens(
                        ServiceConfiguration.ScopedCertificates))
        {
        }

        /// <summary>
        /// Method for setting up claims in the SAML Token issued by the STS
        /// Should be overriden by STS implementations deriving from this base class
        /// to set up appropriate claims
        /// </summary>
        /// <param name="requestSecurityToken"></param>
        /// <returns></returns>
        protected override Collection<SamlAttribute> GetIssuedClaims(RequestSecurityToken requestSecurityToken)
        {
            EndpointAddress rstAppliesTo = requestSecurityToken.AppliesTo;

            if (rstAppliesTo == null)
            {
                FederationUtilities.ThrowTrustFault("No AppliesTo EndpointAddress in RequestSecurityToken");
            }

            EnsureIssuer();

            Collection<SamlAttribute> samlAttributes = new Collection<SamlAttribute>();

            foreach (ClaimSet claimSet in OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets)
            {
                // Only look at claimsets issued by System.
                if (claimSet.Issuer == ClaimSet.System)
                {
                    foreach (Claim claim in claimSet.FindClaims(ClaimTypes.AuthorizationDecision, Rights.PossessProperty))
                    {
                        samlAttributes.Add(new SamlAttribute(claim));
                    }
                    foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Name, Rights.PossessProperty))
                    {
                        samlAttributes.Add(new SamlAttribute(claim));
                    }
                    foreach (Claim claim in claimSet.FindClaims(Constants.Multitenancy.TenantId, Rights.PossessProperty))
                    {
                        samlAttributes.Add(new SamlAttribute(claim));
                    }
                    foreach (Claim claim in claimSet.FindClaims(Constants.Multitenancy.TenantAlias, Rights.PossessProperty))
                    {
                        samlAttributes.Add(new SamlAttribute(claim));
                    }
                }
            }

            return samlAttributes;
        }

        private void EnsureIssuer()
        {
            // Extract the AuthorizationContext from the ServiceSecurityContext
            AuthorizationContext authContext = OperationContext.Current.ServiceSecurityContext.AuthorizationContext;

            // If there are no Claims in the AuthorizationContext, return false
            // The issued token used to authenticate should contain claims 
            if (authContext.ClaimSets == null)
            {
                FederationUtilities.ThrowTrustFault("No claims found.");
            }

            ClaimSet claimSet = FederationUtilities.GetX509CertificateClaimSet(authContext.ClaimSets);

            // Is the ClaimSet was NOT issued by the AuthSTS then return false
            // The AuthzSTS only accepts requests where the client authenticated using a token
            // issued by the AuthSTS.
            if (claimSet == null ||
                !FederationUtilities.IsTrustedIssuer(claimSet.Issuer))
            {
                FederationUtilities.ThrowTrustFault("Untrusted issuer");
            }
        }
    }
}
